<?php
include_once "CF_TableBasic.php";
/**
 * csvTable is a class to output CSV from an array, usually returned form a Database
* @package CFtable
 * @author Chris Tyler
 * @version 1.0
 * @copyright 2007-2008 
 */
Class CF_TableCsv Extends CF_TableBasic{

	// public vars
	var $msg_no_data = 'There is no data avalible for this csv';

	// private vars
	var $is_first_col = true;	
	
	// Functions
	
	function make_row_start($row_num){

	}
	
	/**
	 * make_row_end for CSV - insert line end, and reset first coumn bool
	 * @return string
	 */
	function make_row_end($row_num){
		$this->is_first_col = true; // carefull - that this is always run AFTER the rows are made!	
		return "\n";
	}
	
	/**
	 * make_rowval for CSV - escape the text properly, and only insert a , after the first value
	 * @return string
	 */	
	function make_rowval($currentvalue, $col_name, $current_text){
		if($this->is_first_col){
			$this->is_first_col = false;		
			return csvEscapeText($currentvalue);
			}
		else{
			return ',' . csvEscapeText($currentvalue);
			}
	}
	
	/**
	 * maketable will return the a heading line  (+ line return)  for the csv based on the fieldspec
	 * @return string
	 */		
	function make_heading(){
		if(!is_array($this->fieldspec)){
			return;
		}
		$after_first_col = false;
		foreach($this->fieldspec AS $col_name => $colspec){
			if($after_first_col){
				$headtext .= ',';
				}// if after_first_col = true, then add the comma.  if it is false, then don't.
			if(empty($colspec['headname'])){
				$headtext .= csvEscapeText($col_name);
				}
			else{
				$headname = $colspec['headname'];
				$headtext .= csvEscapeText($headname);
				}
			$after_first_col = true;
			}
		return $headtext . "\n";
	}
	
	/**
	 * export_to_csv will export the csv as a file to the browser.  It will use the current fieldspec and values array.
	 *@param string filename - the full filename (with extension) to use when returning the data.
	 *@param use_heading - Set to true to include a heading (from make_heading) as the first line of the file
	 * @return string
	 */
	function export_to_csv($filename, $use_heading = false){
		if($this->valuesarray){
			if($use_heading){
				$heading = $this->make_heading();
			}
			$csv_file_text = $heading . $this->maketable();
			
			header("Content-type: application/x-msdownload");
			header("Content-Disposition: attachment; filename=$filename");
			header("Pragma: no-cache");
			header("Expires: 0");
			echo $headers.$csv_file_text;
		}
		else{
			print $this->msg_no_data;
			}
	} // end export_to_csv

} // end Class csvTable

?>